package com.list88zhu.android.sunflower.api;

import android.support.v4.util.ArrayMap;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import retrofit2.Retrofit;

/**
 * <pre><code>
 *
 *  </code></pre>
 *
 * @author zhuyingming@qmtv.com
 * @date 2018/9/8
 */
public final class Api {

    private static Lock lock = new ReentrantLock();
    private static ArrayMap<String, ApiProxy> apiProxies = new ArrayMap<>();
    private static ConfigParams params;

    private Api() {
    }



    public static void init(ConfigParams configParams) {
        params = configParams;
    }

    public static ApiProxy provide(Class<? extends Config> clientConfig) {
        if(clientConfig == null) {
            throw new IllegalArgumentException("config can't be null.");
        }
        String clientName = clientConfig.getCanonicalName();
        ApiProxy apiProxy = apiProxies.get(clientName);
        if (apiProxy == null) {
            apiProxy = new ApiProxy(createRetrofit(clientConfig));
            lock.lock();
            apiProxies.put(clientName, apiProxy);
            lock.unlock();
        }
        return apiProxy;
    }

    private static Retrofit createRetrofit(Class<? extends Config> configClass) {
        Retrofit.Builder builder = new Retrofit.Builder();
        try {
            configClass.newInstance().build(builder, params);
        }catch (InstantiationException e) {
            e.printStackTrace();
        }catch (IllegalAccessException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return builder.build();
    }

    /**
     * 基础参数配置
     */
    public static class ConfigParams {
        public boolean isDebug;
        public boolean isOnline;
        public String versionName;
        public String channel;

        @Override
        public String toString() {
            return "ConfigParams {" +
                "isDebug=" +isDebug + "," +
                "isOnline=" + isOnline + "," +
                "versionName='" + versionName + "'," +
                "channel='" + channel +
                "'}";
        }
    }

    /**
     * 接口配置
     */
    public interface Config {
        void build(Retrofit.Builder builder, ConfigParams params);
    }
}
